package com.lanou.moving.singleton;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import com.lanou.moving.base.BaseApplication;
import com.lanou.moving.entity.dao.AddToDao;
import com.lanou.moving.entity.dao.CollectionDao;
import com.lanou.moving.entity.dao.DaoMaster;
import com.lanou.moving.entity.dao.DaoSession;
import com.lanou.moving.entity.dao.RecentlyPlayDao;

/**
 * Created by 刘琪 on 15/11/5.
 */
public class DaoSingleton {

    private static final String DATABASE_NAME = "moving.db";

    private volatile static DaoSingleton instance;

    private SQLiteDatabase db;
    private DaoMaster daoMaster;
    private DaoSession daoSession;
    private Context context;
    private DaoMaster.DevOpenHelper helper;
    private CollectionDao collectionDao;
    private AddToDao addToDao;
    private RecentlyPlayDao recentlyPlayDao;

    private DaoSingleton() {
        context = BaseApplication.getAppContext();
    }

    public static DaoSingleton getInstance() {
        if (instance == null) {
            synchronized (DaoSingleton.class){
                if (instance == null) {
                    instance = new DaoSingleton();
                }
            }
        }
        return instance;
    }

    private DaoMaster.DevOpenHelper getHelper() {
        if (helper == null) {
            helper = new DaoMaster.DevOpenHelper(context,DATABASE_NAME,null);
        }
        return helper;
    }

    private SQLiteDatabase getDb(){
        if (db == null) {
            db = getHelper().getWritableDatabase();
        }
        return db;
    }

    private DaoMaster getDaoMaster() {
        if (daoMaster == null) {
            daoMaster = new DaoMaster(getDb());
        }
        return daoMaster;
    }

    private DaoSession getDaoSession() {
        if (daoSession == null) {
            daoSession = getDaoMaster().newSession();
        }
        return daoSession;
    }

    public CollectionDao getCollectionDao() {
        if (collectionDao == null) {
            collectionDao = getDaoSession().getCollectionDao();
        }
        return collectionDao;
    }

    public AddToDao getAddToDao() {
        if (addToDao == null) {
            addToDao = getDaoSession().getAddToDao();
        }
        return addToDao;
    }

    public RecentlyPlayDao getRecentlyPlayDao() {
        if (recentlyPlayDao == null) {
            recentlyPlayDao = getDaoSession().getRecentlyPlayDao();
        }
        return recentlyPlayDao;
    }

}

